﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Truck.RoadsNamespace
{
    internal abstract class Roads : I_Road
    {
        public event Action<int> RCV_EVENT;
        internal FLAGS flags = new FLAGS();
        internal Roads() 
        {
        }
        public virtual void Dispose()
        {
            //flags归零,关闭所有线程
            flags.L1 = 0;
            flags.L2 = 0;
            //等待所有线程结束
            Task.WaitAll(taskArray);
        }

        public virtual void init(int t = 1)
        {
            //flags初始化
            flags.L1 = 0;
            flags.L2 = 0;
            //初始化线程数组
            taskArray = new Task[t];
        }

        public abstract void send(string filePath);

        public virtual void stopRcv()
        {
            flags.circleRCV_flag = false;
        }

        protected Task[] taskArray;
        public void startRcv(string filePath)
        {
            flags.circleRCV_flag = true;
            for(int i=0;i<taskArray.Length;i++)
            {
                taskArray[i] = Task.Run(() => {
                    while(flags.circleRCV_flag==true)
                    {
                        rcvSingleThread(i);
                    }
                });
            }
        }
        [StructLayout(LayoutKind.Explicit)]
        internal struct FLAGS
        {
            [FieldOffset(0)] internal ulong L1;
            [FieldOffset(8)] internal ulong L2;

            [FieldOffset(0)] internal bool circleRCV_flag;
            [FieldOffset(1)] internal bool flag_2;
            [FieldOffset(2)] internal bool flag_3;
            [FieldOffset(3)] internal bool flag_4;
            [FieldOffset(4)] internal bool flag_5;
            [FieldOffset(5)] internal bool flag_6;
            [FieldOffset(6)] internal bool flag_7;
            [FieldOffset(7)] internal bool flag_8;
            [FieldOffset(8)] internal bool flag_9;
            [FieldOffset(9)] internal bool flag_10;
            [FieldOffset(10)] internal bool flag_11;
            [FieldOffset(11)] internal bool flag_12;
            [FieldOffset(12)] internal bool flag_13;
            [FieldOffset(13)] internal bool flag_14;
            [FieldOffset(14)] internal bool flag_15;
            [FieldOffset(15)] internal bool flag_16;
        }
        /// <summary>
        /// 单线程接收函数
        /// </summary>
        public abstract void rcvSingleThread(int index);
    }
}
